#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: ct_operate_node02.py 
@version:
@time: 2022/06/08 
"""
from TapClientCore.T07_CaseTemplate.v2.CT03_task.ct_task import CTTask, allure, logger, time, check_wait
from copy import deepcopy


class CTTaskNode06Merge(CTTask):
    merge = {}
    name = '自动化-主从合并'

    # merge计算值修改
    def merge_func(self, data):

        """
        一对多
        [{"n": 1, "pk": 1, "title": "mongodb_create",
        "AsMoreList": [{"_id": "62a2412350c9ab2a190e2d12", "pk": 1, "n": 1, "title": "mongodb_create"}]}]

        多对一
        [{"n": 1, "pk": 1, "title": "mongodb_create",
        "AsOneObject": {"_id": "62a2412350c9ab2a190e2d12", "n": 1, "pk": 1, "title": "mongodb_create"}}]

        一对多对一
        [{"n": 1, "pk": 1, "title": "mongodb_create",
        "AsMoreList":
        [{"_id": "62a2412350c9ab2a190e2d12", "pk": 1, "n": 1, "title": "mongodb_create",
        "AsOneObject":
        {"_id": "62a2412350c9ab2a190e2d12", "n": 1, "pk": 1, "title": "mongodb_create"}}]}]
        """
        this_data = deepcopy(data)
        new_data = []
        for one_record in this_data:
            tmp = one_record.copy()
            tmp2 = one_record.copy()
            for k, v in self.merge.items():
                if type(v) is bool:
                    if k == 'AsMoreList':
                        one_record[k] = [tmp]
                    elif k == 'AsOneObject':
                        one_record[k] = tmp
                else:
                    tmp[v] = tmp2
                    one_record[k] = [tmp]
                new_data.append(one_record)
        return new_data

    # merge sort
    @staticmethod
    def merge_data_sort(data, column):
        # 将查询结果按照column序列化
        new_data = []
        for one_record in data:
            tmp = {one: one_record.get(one) for one in column}
            new_data.append(tmp)
        return new_data

    # merge column计算方法
    def merge_column_func(self, data):
        # pk， title -> pk, title, AsMoreList
        # pk， title -> pk, title, AsOneObject
        # pk， title -> pk, title, AsMoreList AsOneObject
        for k, v in self.merge.items():
            if v:
                data.append(k)
        return data

    # merge计算修改节点配置信息
    def MERGE(self, data):
        node_config = data.pop('node_config')
        self.merge = node_config.get('merge')
        # node not update info
        # data['task_config']['node'] = node_config
        return data

    # 全量
    def TASK_MERGE_INITIAL(self, parallel_data):
        data = None
        record_id = None
        task_name = None
        # 随机等待
        self.random_wait()
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)

            record_id = data.get('id')

            operate = data.pop('operate')
            operate_source = operate.get('source')
            source_info = operate_source.get('source_info')
            source_table = operate_source.get('table')
            operate_target = operate.get('target')
            target_info = operate_target.get('target_info')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.MERGE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table

            source_where_column = operate_source.get('where')
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            # stats check
            _stats = operate.get('stats_check').get('initial')
            _stats_initial = _stats.get('insert') + 1

            self.drop_target_table(_target)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)
            # initial stats insert 校验
            with allure.step('任务状态等待'):
                self.scheduled_task_wait_it_complete(task_name)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # column_check
            column = self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_column_func
            )
            # check
            self.tap_merge_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
        finally:
            self.release_table(record_id)
            self.generate_task_url(task_name, data.get('task_type'))
            logger.info(self.task_url)
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 增量
    def TASK_MERGE_CDC(self, parallel_data):
        data = None
        # 随机等待
        self.random_wait()
        record_id = None
        source_delete = None
        task_name = None
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')

            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.MERGE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            # stats check
            _stats = operate.get('stats_check').get('cdc')
            # _stats_initial = _stats.get('initial') + 1
            _stats_insert = _stats.get('insert') + 1
            _stats_update = _stats.get('update') + 1
            _stats_delete = _stats.get('delete') + 1
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)
            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 增量任务等待时间
            logger.info('等待一段时间')
            time.sleep(180)
            # insert
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # column_check
            column = self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_column_func
            )
            # check
            self.tap_merge_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # update check
            self.tap_merge_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # delete check
            self.tap_merge_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 全量 + 增量
    def TASK_MERGE_INITIAL_CDC(self, parallel_data):
        data = None
        source_delete = None
        record_id = None
        _source = None
        _target = None
        task_name = None
        try:
            # 随机等待
            self.random_wait()
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')
            # connector
            _source = self.init_connector(source_info)
            _target = self.init_connector(target_info)
            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            task_name = data.get('task_config').get('config').get('name')

            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            data = self.MERGE(data)

            # stats check
            _stats = operate.get('stats_check').get('initial+cdc')
            _stats_initial = _stats.get('initial') + 1
            _stats_insert = _stats.get('insert') + _stats_initial
            _stats_update = _stats.get('update') + 1
            _stats_delete = _stats.get('delete') + 1
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)

            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 全量阶段校验
            logger.info('initial check')
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            column = self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_column_func
            )
            # initial check
            self.tap_merge_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
            # 增量阶段校验
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # insert check
            self.tap_merge_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            # update check
            self.tap_merge_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # delete check
            self.tap_merge_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.merge_func,
                self.merge_data_sort,
                column
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass
